# import json
#
# from django.contrib.auth import login
# from django.http import JsonResponse
# import re
#
# # Create your views here.
# from django.views import View
# from django.contrib.auth import logout
# from apps.users.models import User
# from apps.users.utils import generic_email_verify_token
#
#
# #### 用户数量 #########
# class UsernameCountView(View):
#     def get(self, request, username):
#         count = User.objects.filter(username=username).count()
#         return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})
#
#
# ##### 用户注册验证 #######
# class RegisterView(View):
#     def post(self, request):
#         # 1. 接收参数
#         body_bytes = request.body
#         body_str = body_bytes.decode()
#         body_dict = json.loads(body_str)
#         # 2. 获取数据
#         username = body_dict.get('username')
#         password = body_dict.get('password')
#         password2 = body_dict.get('password2')
#         mobile = body_dict.get('mobile')
#         allow = body_dict.get('allow')
#         # 3. 验证数据
#         # all里的元素只要是none就返回false
#         if not all([username, password, password2, mobile, allow]):
#             return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
#         # 用户名满足规则,用户名不能重复
#         if not re.match(r'[a-zA-Z_-]{5,20}', username):
#             return JsonResponse({'code': 400, 'errmsg': '用户名格式错误'})
#         # 密码满足规则
#         if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
#             return JsonResponse({'code': 400, 'errmsg': '密码格式错误'})
#         # 两次密码输入一致
#         if password != password2:
#             return JsonResponse({'code': 400, 'errmsg': '两次密码输入不一致'})
#         # 手机号格式正确
#         if not re.match(r'^1[345789]\d{9}$', mobile):
#             return JsonResponse({'code': 400, 'errmsg': '手机号格式错误'})
#         # 协议勾选
#         if not allow:
#             return JsonResponse({'code': 400, 'errmsg': '请勾选用户协议'})
#         # 4. 数据入库
#         # User=User(username=username, password=password, mobile=mobile)
#         # User.save()
#         # User.objects.create(username=username, password=password, mobile=mobile)
#         user = User.objects.create_user(username=username, password=password, mobile=mobile)
#         # 状态保持
#         login(request, user)
#         # 5. 返回响应
#         return JsonResponse({'code': 0, 'errmsg': 'ok'})
#
#
# #### 登录验证 #######
# class LoginView(View):
#     def post(self, request):
#         # 1. 接收参数
#         data = json.loads(request.body.decode())
#         username = data.get('username')
#         password = data.get('password')
#         remembered = data.get('remembered')
#         # 2. 验证参数
#         if not all([username, password]):
#             return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
#         # 确定我们根据的是手机号还是用户名
#         if re.match(r'^1[3-9]\d{9}$', username):
#             # 手机号登录
#             User.USERNAME_FIELD = 'mobile'
#         else:
#             # 用户名登录
#             User.USERNAME_FIELD = 'username'
#         # 3. 验证用户和密码
#         from django.contrib.auth import authenticate
#         user = authenticate(username=username, password=password)
#         if user is None:
#             return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
#         # 4. 状态保持session
#         from django.contrib.auth import login
#         login(request, user)
#         # 5. 判断是否记得登录
#         if remembered:
#             # 记住登录
#             request.session.set_expiry(None)
#         else:
#             # 不记住登录
#             request.session.set_expiry(0)
#         # 6. 返回响应
#         response = JsonResponse({'code': 0, 'errmsg': 'ok'})
#         # 显示首页用户名
#         response.set_cookie('username', username)
#         return response
# #### 退出登录 #######
# class LogoutView(View):
#     def delete(self, request):
#         # 删除session
#         logout(request)
#         response = JsonResponse({'code': 0, 'errmsg': 'ok'})
#         # 删除cookie
#         response.delete_cookie('username')
#         return response
# from utils.views import LoginRequiredJSONMixin
# ########## 用户中心 #########
# class CenterView(LoginRequiredJSONMixin, View):
#     def get(self, request):
#         info_data = {
#             'username': request.user.username,
#             'email': request.user.email,
#             'mobile': request.user.mobile,
#             'email_active': request.user.email_active
#         }
#         return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})
# ##### 用户中心邮箱 #########
# class EmailView(LoginRequiredJSONMixin, View):
#     def put(self, request):
#         data = json.loads(request.body.decode())
#         # 获取数据
#         email = data.get('email')
#         # 验证数据
#         if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
#             return JsonResponse({'code': 400, 'errmsg': '邮箱格式错误'})
#         # 保存邮箱信息
#         user = request.user
#         user.save()
#         # 发送验证邮件
#         from django.core.mail import send_mail
#         # 邮件标题
#         subject = '美多商城激活邮件'
#         # 邮件内容
#         message = ''
#         # 收件人列表
#         recipient_list = [email]
#         # 发件人
#         from_email = '18760602957@163.com'
#         token = generic_email_verify_token(request.user.id)
#         verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s' % token
#         # 组织我们的激活邮件
#         html_message = "<p>尊敬的用户您好！</p>\n" \
#                        "<p>感谢您使用美多商城·</p>\n" \
#                        "<p>您的邮箱为：%s，请点击此链接激活您的邮箱：</p>\n" \
#                        "<p><a href=\"%s\">%s</a></p>" % (email, verify_url, verify_url)
#
#         # send_mail(subject=subject,
#         #           message=message,
#         #           from_email=from_email,
#         #           recipient_list=recipient_list,
#         #           html_message=html_message)
#         from celery_tasks.email.tasks import celery_send_email
#         celery_send_email.delay(
#             subject=subject,
#             message=message,
#             from_email=from_email,
#             recipient_list=recipient_list,
#             html_message=html_message)
#
#         # 返回响应
#         return JsonResponse({'code': 0, 'errmsg': 'ok'})
#
#
#
#
#上面的版本是用celery异步发送版本，下面是同步发送版本：
import json
from django.contrib.auth import login
from django.http import JsonResponse
import re
from apps.users.models import Address
# Create your views here.
from django.views import View
from django.contrib.auth import logout
from apps.users.models import User
from apps.users.utils import generic_email_verify_token
from apps.goods.models import SKU
from django_redis import get_redis_connection

#### 用户数量 #########
class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})
##### 用户注册验证 #######
class RegisterView(View):
    def post(self, request):
        # 1. 接收参数
        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)
        # 2. 获取数据
        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')
        # 3. 验证数据
        # all里的元素只要是none就返回false
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 用户名满足规则,用户名不能重复
        if not re.match(r'[a-zA-Z_-]{5,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名格式错误'})
        # 密码满足规则
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式错误'})
        # 两次密码输入一致
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码输入不一致'})
        # 手机号格式正确
        if not re.match(r'^1[345789]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式错误'})
        # 协议勾选
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': '请勾选用户协议'})
        # 4. 数据入库
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 状态保持
        login(request, user)
        # 5. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
#### 登录验证 #######
class LoginView(View):
    def post(self, request):
        # 1. 接收参数
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        # 2. 验证参数
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 确定我们根据的是手机号还是用户名
        if re.match(r'^1[3-9]\d{9}$', username):
            # 手机号登录
            User.USERNAME_FIELD = 'mobile'
        else:
            # 用户名登录
            User.USERNAME_FIELD = 'username'
        # 3. 验证用户和密码
        from django.contrib.auth import authenticate
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
        # 4. 状态保持session
        from django.contrib.auth import login
        login(request, user)

        # 5. 判断是否记得登录
        if remembered:
            # 记住登录
            request.session.set_expiry(None)
        else:
            # 不记住登录
            request.session.set_expiry(0)
        # 6. 返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 显示首页用户名
        response.set_cookie('username', username)
        # 必须是登录后合并购物车
        from apps.carts.utils import merge_cookie_to_redis
        response = merge_cookie_to_redis(request, response)
        return response
#### 退出登录 #######
class LogoutView(View):
    def delete(self, request):
        # 删除session
        logout(request)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 删除cookie
        response.delete_cookie('username')
        return response
from utils.views import LoginRequiredJSONMixin
########## 用户中心 #########
class CenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        info_data = {
            'username': request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_active': request.user.email_active
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})
##### 用户中心邮箱 #########
class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):
        data = json.loads(request.body.decode())
        # 获取数据
        email = data.get('email')
        # 验证数据
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400, 'errmsg': '邮箱格式错误'})
        # 保存邮箱信息
        user = request.user
        user.save()
        # 发送验证邮件
        from django.core.mail import send_mail
        # 邮件标题
        subject = '美多商城激活邮件'
        # 邮件内容
        message = ''
        # 收件人列表
        recipient_list = [email]
        # 发件人
        from_email = '18760602957@163.com'
        token = generic_email_verify_token(request.user.id)
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s' % token
        # 组织我们的激活邮件
        html_message = "<p>尊敬的用户您好！</p>\n" \
                       "<p>感谢您使用美多商城·</p>\n" \
                       "<p>您的邮箱为：%s，请点击此链接激活您的邮箱：</p>\n" \
                       "<p><a href=\"%s\">%s</a></p>" % (email, verify_url, verify_url)

        # 注释掉原来使用 Celery 发送邮件的代码
        # from celery_tasks.email.tasks import celery_send_email
        # celery_send_email.delay(
        #     subject=subject,
        #     message=message,
        #     from_email=from_email,
        #     recipient_list=recipient_list,
        #     html_message=html_message)

        # 使用同步的方式发送邮件
        send_mail(subject=subject,
                  message=message,
                  from_email=from_email,
                  recipient_list=recipient_list,
                  html_message=html_message)

        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
#### 邮箱验证 #######
class EmailVerifyView(View):
    def put(self, request):
        # 1. 接收参数
        params = request.GET
        token = params.get('token')
        # 2. 验证参数
        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '缺少token'})
        # 3. 解密token
        from apps.users.utils import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        # 4. 查询用户
        user = User.objects.get(id=user_id)
        # 5. 修改email_active的值为True
        user.email_active = True
        user.save()
        # 6. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
#### 地址管理视图 #######
class AddressCreateView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 原有新增逻辑
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式错误'})
        if email and not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400, 'errmsg': '邮箱格式错误'})

        address = Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def put(self, request, address_id):
        # 判断是否是设置默认地址
        if request.path.endswith('/default/'):
            try:
                address = Address.objects.get(id=address_id, user=request.user)
                # 假设 Address 模型有 is_default 字段
                Address.objects.filter(user=request.user, is_default=True).update(is_default=False)
                address.is_default = True
                address.save()
                return JsonResponse({'code': 0, 'errmsg': '设为默认地址成功'})
            except Address.DoesNotExist:
                return JsonResponse({'code': 400, 'errmsg': '地址不存在'})
        else:
            # 修改地址
            data = json.loads(request.body.decode())
            receiver = data.get('receiver')
            province_id = data.get('province_id')
            city_id = data.get('city_id')
            district_id = data.get('district_id')
            place = data.get('place')
            mobile = data.get('mobile')
            tel = data.get('tel')
            email = data.get('email')

            if not all([receiver, province_id, city_id, district_id, place, mobile]):
                return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                return JsonResponse({'code': 400, 'errmsg': '手机号格式错误'})
            if email and not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '邮箱格式错误'})

            try:
                address = Address.objects.get(id=address_id, user=request.user)
                address.receiver = receiver
                address.title = receiver
                address.province_id = province_id
                address.city_id = city_id
                address.district_id = district_id
                address.place = place
                address.mobile = mobile
                address.tel = tel or ''
                address.email = email or ''
                address.save()
            except Address.DoesNotExist:
                return JsonResponse({'code': 400, 'errmsg': '地址不存在'})

            address_dict = {
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            }
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def delete(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id, user=request.user)
        except Address.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '地址不存在'})
        address.delete()
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
#####显示地址列表#####
class AddressView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        addresses = Address.objects.filter(user=user, is_deleted=False)
        # 将对象列表转换为字典列表
        address_list = []
        for address in addresses:
            address_list.append({
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_list})
####展示浏览记录####
class UserHistoryView(LoginRequiredJSONMixin, View):

    def post(self, request):
        user = request.user

        # 1. 接收请求
        data = json.loads(request.body.decode())
        # 2. 获取请求参数
        sku_id = data.get('sku_id')
        # 3. 验证参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此商品'})
        # 4. 连接redis    list
        redis_cli = get_redis_connection('history')
        # 5. 去重(先删除 这个商品id 数据，再添加就可以了)
        redis_cli.lrem('history_%s' % user.id, 0, sku_id)
        # 6. 保存到redsi中
        redis_cli.lpush('history_%s' % user.id, sku_id)
        # 7. 只保存5条记录
        redis_cli.ltrim("history_%s" % user.id, 0, 4)
        # 8. 返回JSON
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

    def get(self, request):
        # 1. 连接redis
        redis_cli = get_redis_connection('history')
        # 2. 获取redis数据（[1,2,3]）
        ids = redis_cli.lrange('history_%s' % request.user.id, 0, 4)
        # [1,2,3]
        # 3. 根据商品id进行数据查询
        history_list = []
        for sku_id in ids:
            sku = SKU.objects.get(id=sku_id)
            # 4. 将对象转换为字典
            history_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        # 5. 返回JSON
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': history_list})
